<template>
	<div class="wrapper xinJian">
		<myhead activeIndex="/video"></myhead>
		<div class="content">
			<div class="content-item1">
				<div class="information">
					<h3>
						<el-icon style="margin-right: 5px"> <Connection /> </el-icon>基本信息
					</h3>
				</div>
				<div class="information-text">知识库 {{ titileName }}</div>
				<div class="information information-content">
					<el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
						<el-form-item label="标题" prop="title">
							<el-input placeholder="请输入标题" v-model="form.title" class="width-item" />
						</el-form-item>
						<el-form-item label="作者" prop="auth" ref="elFormItemAuthRef">
							<v-department
								v-model="form.auth"
								:placeholder="'请选择作者'"
								:title="'选择作者'"
								:placeholders="'请输入用户名进行搜索'"
								@close="onAuthClose"
							></v-department>
						</el-form-item>
						<el-form-item label="发布部门" prop="deptId" ref="elFormItemAuthRefs">
							<v-bumen
								v-model="form.deptId"
								:placeholder="'请选择部门'"
								:title="'选择部门'"
								:placeholders="'请输入部门进行搜索'"
								@close="onDeptClose"
							></v-bumen>
						</el-form-item>
						<el-form-item label="发布时间" prop="pubTime">
							<el-date-picker
								class="width-item"
								v-model="form.pubTime"
								type="date"
								placeholder="选择发布日期"
								value-format="YYYY-MM-DD"
								@blur="timeChange"
							>
							</el-date-picker>
						</el-form-item>
						<el-form-item label="过期时间">
							<div style="display: flex; flex-direction: column">
								<el-date-picker
									:disabled-date="disabledDate"
									class="width-item"
									v-model="form.expTime"
									type="date"
									placeholder="选择过期日期"
									value-format="YYYY-MM-DD 00:00:00"
								>
								</el-date-picker>
								<div style="font-size: 12px; color: #ccc">
									为空表示永不过期，过期后将自动变为草稿（草稿仅自己可见）
								</div>
							</div>
						</el-form-item>
						<el-form-item label="所属分类" prop="categoryId">
							<el-select class="width-item" v-model="form.categoryId" placeholder="请选择分类">
								<el-option
									v-for="item in classification"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								>
								</el-option>
							</el-select>
							<!-- <el-input class="width-item"></el-input> -->
						</el-form-item>
						<el-form-item label="标签">
							<div class="width-item-label">
								<v-select-tags v-model="form.label" :isShow="false">
									<template #tags="{ onOpenDialog, onDelete, selectedNames }">
										<div v-if="selectedNames.length">
											<el-tag v-for="(item, index) in selectedNames" class="mx-1">
												<!-- @close="onDelete(index)" -->
												<!-- closable -->
												{{ item }}
											</el-tag>
											<el-button type="primary" @click="onOpenDialog">添加标签</el-button>
										</div>
										<div v-else class="width-item">
											<el-input
												type="text"
												placeholder="请选择标签"
												readonly
												@click="onOpenDialog"
											>
											</el-input>
										</div>
									</template>
								</v-select-tags>
							</div>
						</el-form-item>
						<el-form-item label="摘要" prop="remark">
							<el-input
								placeholder="请输入摘要"
								v-model="form.remark"
								class="width-item"
								type="textarea"
								maxlength="200"
								show-word-limit
								:autosize="{
									minRows: 3,
									maxRows: 10,
								}"
							/>
						</el-form-item>
						<el-form-item label="封面上传" prop="cover">
							<el-upload
								class="avatar-uploader"
								action="/"
								:before-upload="beforeAvatarUpload"
								:http-request="upfile"
								:show-file-list="false"
							>
								<img v-if="form.cover" :src="form.cover" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon">
									<Plus />
								</el-icon>
								<template #tip>
									<div class="el-upload__tip">只能上传jpg/png文件</div>
								</template>
							</el-upload>
						</el-form-item>
						<el-form-item label="视频上传" prop="videos">
							<el-upload
								v-model="form.videos"
								:before-upload="beforeAvatarUploads"
								:http-request="upfiles"
								:show-file-list="true"
								action="/"
								multiple
								:limit="2"
								:file-list="form.videos"
							>
								<template #file>
									<div v-for="(item, index) in form.videos" :key="index">
										<div>
											{{ item.name }}
											<span class="videoList" @click="delVideo(index)"
												><el-icon> <Close /> </el-icon
											></span>
										</div>
									</div>
								</template>
								<el-button type="primary">点击上传附件</el-button>
								<template #tip>
									<div class="el-upload__tip">请上传MP4格式的视频文件</div>
								</template>
							</el-upload>
						</el-form-item>
						<el-form-item>
							<el-button @click="quxiao">取消</el-button>
							<el-button v-loading="loading" @click="submit('draft')" type="warning">保存草稿</el-button>
							<el-button v-loading="loading" type="primary" @click="submit('sub')">提交</el-button>
						</el-form-item>
					</el-form>
				</div>
			</div>
		</div>
		<v-myfoot></v-myfoot>
	</div>
</template>

<script setup>
import { useDictStore } from "/store/dict"
import { watch } from "vue"
// import { getAxios, postAxios } from "/axios"
import vSelectTags from "/packages/v-select-tags/index.vue"
import { Upload, Search, Close, Plus } from "@element-plus/icons-vue"
const { proxy } = getCurrentInstance()
import { ElMessage } from "element-plus"

const form = reactive({
	title: "", //标题
	auth: [], //作者
	deptId: [], //部门
	pubTime: "", //发布时间
	expTime: "", //过期时间
	label: [], //标签
	remark: "", //标签
	cover: "", //封面
	videos: [], //视频
	categoryId: "",
	modelId: "",
})
const loading = ref(false)
const beforeAvatarUpload = rawFile => {
	if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
		ElMessage.error("请上传png/jpeg格式文件")
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("图片大小不能超过2MB!")
		return false
	}
	return true
}
const beforeAvatarUploads = rawFile => {
	if (rawFile.type !== "video/mp4") {
		ElMessage.error("请上传mp4格式文件")
		return false
	}
	return true
}
//效验
const rules = reactive({
	title: [{ required: true, message: "请输入标题", trigger: "blur" }],
	auth: [{ required: true, message: "请选择作者", trigger: "change" }],
	deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
	pubTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
	cover: [{ required: true, message: "请上传一个封面", trigger: "blur" }],
	videos: [{ required: true, message: "最少上传一个视频附件", trigger: "blur" }],
	categoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
	remark: [{ required: true, message: "请输入摘要", trigger: "blur" }],
})

// 提取关键字
const selectTags = ref()
const dictSrc = ref([])
const pubTimes = ref(new Date())
//清空
function clean() {
	form.title = ""
	form.auth = []
	form.deptId = []
	form.pubTime = ""
	form.categoryId = ""
	form.expTime = ""
	form.label = []
	form.remark = ""
	form.cover = ""
	form.videos = []
}
const route = useRoute()
const titileName = ref("")
const router = useRouter()
//标签弹窗
const labelL = ref(true)
const formRef = ref()
//分类
const tagList = ref({})
const classification = ref([])
async function cread() {
	if (route.query.name) {
		titileName.value = route.query.name
	}
	//动态渲染
	//用户标签
	tagList.value = await getAxios(`/knowledge/kbBasicLabel/list?bId=${route.query.id}`)
	const resAdd = await getAxios(`/knowledge/kbCategory/findBySwWidToBackstageAdd?swId=${route.query.swId}`)
	classification.value = resAdd
	if (route.query.id) {
		form.categoryId = route.query.id
	}

	if (route.query.edit == "2") {
		try {
			const res = await getAxios(`/knowledge/kbVideo/findByIdVideo?num=1&id=${route.query.id}`)
			titileName.value = res.subjectWarehouseName
			form.title = res.title
			form.auth[0] = {
				realName: res.authName,
				id: res.auth,
			}
			form.deptId[0] = {
				name: res.deptName,
				id: res.deptId,
			}
			form.pubTime = res.pubTime
			form.categoryId = res.categoryId
			form.expTime = res.expTime
			form.label = tagList.value || []
			form.remark = res.remark
			form.cover = res.cover
			form.videos = res.videoSrc || []
		} catch (error) {
			form.categoryId = ""
			ElMessage.error(error)
		}
	} else {
		const userInfo = JSON.parse(localStorage.getItem("userInfo"))
		form.auth[0] = {
			realName: userInfo.realName,
			id: userInfo.id,
		}
	}
}
cread()

const elFormItemAuthRef = ref()
const elFormItemAuthRefs = ref()

function onAuthClose() {
	elFormItemAuthRef.value.clearValidate()
}
function onDeptClose() {
	elFormItemAuthRefs.value.clearValidate()
}
const upfile = async params => {
	const file = params.file
	const formData = new FormData()
	formData.append("upfile", file)
	const { url } = await postAxios("/system/oss/upload", formData)
	form.cover = url
}
const upfiles = async params => {
	const file = params.file
	const formData = new FormData()
	formData.append("upfile", file)
	const res = await postAxios("/system/oss/upload", formData)
	form.videos = [res]
}
//视频删除
const delVideo = index => {
	form.videos.splice(index, 1)
}
const fabu = ref(false)
//提交
const submit = async item => {
	loading.value = true
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		try {
			await formRef.value.validate()
			let src = {}
			src.title = form.title
			src.auth = form.auth[0].id
			src.deptId = form.deptId[0].id
			src.pubTime = form.pubTime
			src.expTime = form.expTime
			// src.label = form.label
			src.cover = form.cover
			src.videoSrc = form.videos
			src.categoryId = form.categoryId
			src.remark = form.remark
			let listLabel = []
			form.label.forEach(items => {
				listLabel.push({
					name: items.name,
					status: items.status,
				})
			})
			src.labels = listLabel
			if (item == "sub") {
				if (route.query.edit == 2) {
					try {
						src.id = route.query.id
						src.status = 1
						await postAxios("/knowledge/kbVideo/edit", src)
						ElMessage.success("修改成功")
						loading.value = false
						router.back()
						clean()
					} catch (error) {
						ElMessage.error(error)
						loading.value = true
					}
				} else {
					try {
						src.status = 1
						await postAxios("/knowledge/kbVideo/save", src)
						ElMessage.success("保存成功")
						loading.value = false
						router.back()
						clean()
					} catch (error) {
						ElMessage.error(error)
						loading.value = true
					}
				}
			} else {
				try {
					src.id = route.query.id
					src.status = 2
					await postAxios("/knowledge/kbVideo/edit", src)
					ElMessage.success("保存草稿成功")
					loading.value = false
					router.back()
					clean()
				} catch (error) {
					ElMessage.error(error)
					loading.value = true
					fabu.value = false
				}
			}
		} catch (error) {
			fabu.value = false
			ElMessage.error("请输入必填项")
			loading.value = false
		}
	}
}
const disabledDate = time => {
	return time.getTime() < Date.now()
}
function addZero(s) {
	return s < 10 ? "0" + s : s
}
const timeChange = () => {
	let date = new Date()
	form.pubTime =
		form.pubTime +
		" " +
		addZero(date.getHours()) +
		":" +
		addZero(date.getMinutes()) +
		":" +
		addZero(date.getSeconds())
}
const quxiao = () => {
	if (route.query.edit == 2) {
		router.push(`/videoDetails?id=${route.query.id}&swId=${route.query.swId}`)
	} else {
		router.go(-1)
	}
}
</script>
<style lang="scss" scoped>
@import "/style/basis";

.xinJian {
	background-color: #f8f8f8;

	.content {
		width: 100%;
		padding: 25px 50px;
		height: 80vh;
		background-color: #f8f8f8;
		border-radius: 10px;
		display: flex;

		@include maxWidth(450) {
			padding: 5px 0px;
		}

		.content-item1 {
			text-align: center;

			background-color: #fff;
			width: 100%;
			height: 100%;
			padding: 20px 40px;
			// border-right: 3px solid #ccc;
			overflow: auto;

			.information {
				margin: 20px 0;
			}

			.information-content {
				display: flex;
				justify-content: center;
				padding-left: 200px;

				@include maxWidth(768) {
					padding-left: 100px;
				}

				@include maxWidth(600) {
					padding-left: 50px;
				}

				@include maxWidth(500) {
					padding-left: 0px;
				}

				// margin-left: 40px;
				:deep(.el-upload) {
					border: 1px dashed #999;
				}
			}

			.information-text {
				padding-left: 30px;
				margin-bottom: 40px;
			}
		}

		.content-item1::-webkit-scrollbar {
			overflow: -moz-hidden-unscrollable;
		}
	}

	::v-deep .el-input-group__append {
		background-color: #2972fa;
		color: #fff;
		box-shadow: 0 0 0;
	}

	.el-checkbox-button {
		margin: 10px;
	}

	::v-deep.el-checkbox-button__inner {
		border: 0 !important;
	}

	.el-upload__tip {
		margin-left: 10px;
	}

	.el-scrollbar {
		display: none;
	}

	.bq {
		padding: 10px 20px;
		text-align: center;
		margin: 10px 20px;
		border-radius: 30px;
		cursor: pointer;
		background-color: #f4f4f4;
	}

	.label-item {
		margin-top: 20px;
		padding: 20px 40px;
		border-top: 1px solid #2972fa;
		border-bottom: 1px solid #2972fa;
		display: flex;
		justify-content: space-between;
		line-height: 2;
	}

	.checkbox {
		margin: 20px 0;
		display: flex;
		justify-content: space-between;
	}

	.operate {
		margin-top: 20px;
		display: flex;
		justify-content: flex-end;
	}

	.selectColor {
		background-color: #2972fa;
	}

	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.avatar-uploader .el-upload {
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		// transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.selectDel {
		cursor: pointer;
		margin-left: 15px;
		width: 75px;
	}

	.videoList {
		margin-left: 15px;
	}
}

.width-item {
	width: 250px;

	@include maxWidth(450) {
		width: 200px;
	}
}

:deep(.el-date-editor.el-input) {
	width: 250px;

	@include maxWidth(450) {
		width: 200px;
	}
}

.width-item-label {
	width: 400px;
	text-align: left;

	@include maxWidth(768) {
		width: 250px;
	}

	.mx-1 {
		margin-right: 10px;
	}
}
</style>
